﻿using Microsoft.Extensions.DependencyInjection;
using MqttAnalyze.Data.Blls;
using System.Configuration;
using System.Data;
using System.IO;
using System.Windows;
using System.Windows.Forms.Design;
using System.Windows.Markup;
using WpfMqttAnalyzeApp.Model;
using WpfMqttAnalyzeApp.Services;

namespace WpfMqttAnalyzeApp
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private IServiceProvider _serviceProvider;
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            try
            {
                //Todo
                var services = new ServiceCollection();
                var userData = new UserData();
                var jsonStr = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "userData.json"));
                var jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject<UserData>(jsonStr);
                if (jsonObject != null)
                {
                    userData = jsonObject;
                }
                // 注册你的服务
                var mqttService = new MqttMsgService();
                var mqttBll = new MqttDataBLL(userData.DbPath ?? @".\DataBase\mqtt.db");

                services.AddSingleton<IMqttMsgService>(mqttService);
                services.AddSingleton<IMqttDataBLL>(mqttBll);

                _serviceProvider = services.BuildServiceProvider();
                ResourceHelper.InitLanguageList();
            }
            catch (System.Exception ex)
            {
                System.Windows.MessageBox.Show("应用启动失败，错误信息：" + ex.Message);
                Application.Current.Shutdown();
            }
        }

        public T GetService<T>() where T : class
        {
            return _serviceProvider.GetService<T>();
        }
    }

}
